<template>
  <div class="app-container">
    <div class="container">
      <!--工具栏-->
      <div>
        <el-form ref="query" :inline="true" :model="query" size="small" class="demo-form-inline">
          <el-form-item label="团队名称：">
            <el-input
              v-model="query.team_name"
              clearable
              placeholder="输入团队名称"
              style="width: 180px;"
              class="filter-item"
              @keyup.enter.native="toQuery"/>
          </el-form-item>
          <el-form-item label="团队负责人：">
            <el-input
              v-model="query.leader_name"
              clearable
              placeholder="输入团队负责人"
              style="width: 180px;"
              class="filter-item"
              @keyup.enter.native="toQuery"/>
          </el-form-item>
          <el-form-item label="联系电话：">
            <el-input
              v-model="query.phone"
              clearable
              placeholder="输入联系电话"
              style="width: 180px;"
              class="filter-item"
              @keyup.enter.native="toQuery"/>
          </el-form-item>
          <el-form-item label="状态：">
            <el-select v-model="query.state" clearable placeholder="状态" class="filter-item" style="width: 180px">
              <el-option v-for="item in stateOptions" :key="item.key" :label="item.name" :value="item.key"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button size="mini" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
            <el-button size="mini" type="primary" icon="el-icon-search" @click="toQuery">搜索</el-button>
          </el-form-item>
        </el-form>
        <div class="operate-container">
          <el-button
            class="filter-item"
            size="mini"
            type="primary"
            icon="el-icon-plus"
            @click="add">新增团队
          </el-button>
        </div>
      </div>
      <!--表格渲染-->
      <el-table v-loading="loading" :data="data" size="small" style="width: 100%;">
        <el-table-column
          label="序号"
          width="70px"
          align="center">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column
          label="团队ID"
          align="center"
          prop="team_id"/>
        <el-table-column ref="table" :show-overflow-tooltip="true" label="团队名称" align="center" prop="team_name"/>
        <el-table-column label="团队负责人" prop="leader_name" width="80px" align="center"/>
        <el-table-column label="联系电话" prop="phone" show-overflow-tooltip align="center"/>
        <el-table-column label="状态" align="center" width="70px" show-overflow-tooltip>
          <template slot-scope="scope" width="70px">
            <span v-if="scope.row.state == 0">正常</span>
            <span v-else>关闭</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" align="center"/>
        <el-table-column label="创建时间" prop="create_date" align="center"/>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <!--发布评论触发事件-->
            <!--编辑按钮-->
            <span class="btn" @click="enterBank(scope.row)">编辑</span>
            <span class="btn" @click="getcode(scope.row)">团码</span>
            <!--删除触发事件-->
            <el-popover
              :ref="scope.row.team_id"
              placement="top"
              width="180">
              <p>确定删除本条评论吗？</p>
              <div style="text-align: right; margin: 0">
                <el-button size="mini" type="text" @click="$refs[scope.row.team_id].doClose()">取消</el-button>
                <el-button :loading="delLoading" type="primary" size="mini" @click="subDelete(scope.row)">确定</el-button>
              </div>
              <span slot="reference" class="btn">删除</span>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog
        :visible.sync="code_show"
        title="团队推广二维码"
        width="500px"
        height="500">
        <div class="code_con">
          <div id="qrcode" class="code" />
          <span class="teamname">{{ teamname }}</span>
          <span class="downcode" @click="downcode">下载二维码</span>
        </div>
      </el-dialog>
      <!--分页组件-->
      <el-pagination
        :total="total"
        :current-page="page + 1"
        background
        style="margin-top: 8px;"
        layout="total, prev, pager, next, sizes"
        @size-change="sizeChange"
        @current-change="pageChange"/>
    </div>
  </div>
</template>

<script>
import initData from '@/mixins/initData'
import { deleteTeam } from '@/api/mall/team'
import QRCode from 'qrcodejs2' // 引入qrcode
import { mapGetters } from 'vuex'
export default {
  mixins: [initData],
  data() {
    return {
      levelTypeOptions: [
        { key: '1', display_name: '商品评价' },
        { key: '100', display_name: '商城反馈' }
      ],
      stateOptions: [
        { key: '0', name: '正常' },
        { key: '1', name: '关闭' }
      ],
      query: {
        team_name: '',
        leader_name: '',
        phone: '',
        state: ''
      },
      delLoading: false,
      releaseLoading: false,
      teamcode: '',
      code_show: false,
      teamname: ''
    }
  },
  computed: {
    ...mapGetters([
      'user'
    ])
  },
  destroyed() {
    // 页面销毁事件
    window.localStorage.removeItem('teamList')
  },
  created() {
    // 获取存储的值，通过该值判断该页面有没有做刷新操作，若有做刷新，则跳转首页
    const refresh = window.localStorage.getItem('teamList')
    if (refresh === 'hello') {
      this.$router.push({ path: '/chaomall/home' })
    } else {
      window.localStorage.setItem('teamList', 'hello')
    }
    // 加载数据
    this.$nextTick(() => {
      this.init()
    })
  },
  mounted() {

  },
  methods: {
    beforeunloadFn(e) {
      // 销毁
      window.localStorage.setItem('Refresh', 1)
    },
    getQrocde(team_code) {
      if (document.getElementById('qrcode')) {
        document.getElementById('qrcode').innerHTML = ''
      }
      this.$nextTick(function() { // 生成二维码
        this.qrcode(team_code)
      })
    },
    qrcode(team_code) {
      const code = !team_code ? '*' : team_code
      new QRCode('qrcode', {
        width: 130,
        height: 130, // 高度
        text: process.env.URL_H5_INDEX + 'pages/homepage/homepage?param=2,' + code + ',*', // 二维码内容
        render: 'canvas', // 设置渲染方式（有两种方式 table和canvas，默认是canvas）
        background: '#f0f', // 背景色
        foreground: '#ff0' // 前景色
      })
    },
    downcode() {
      // //找到canvas标签
      const myCanvas = document.getElementById('qrcode').getElementsByTagName('canvas')
      const img = document.getElementById('qrcode').getElementsByTagName('img')
      // // //创建一个a标签节点
      const a = document.createElement('a')
      // //设置a标签的href属性（将canvas变成png图片）
      const imgURL = myCanvas[0].toDataURL('image/jpg')
      const ua = navigator.userAgent
      if (ua.indexOf('Trident') !== -1 && ua.indexOf('Windows') !== -1) { // IE内核 并且  windows系统 情况下 才执行;
        const bstr = atob(imgURL.split(',')[1])
        let n = bstr.length
        const u8arr = new Uint8Array(n)
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n)
        }
        const blob = new Blob([u8arr])
        window.navigator.msSaveOrOpenBlob(blob, '下载' + '.' + 'png')
      } else if (ua.indexOf('Firefox') > -1) { // 火狐兼容下载
        const blob = this.base64ToBlob(imgURL) // new Blob([content]);
        const evt = document.createEvent('HTMLEvents')
        evt.initEvent('click', true, true)// initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
        a.download = ' '// 下载图片名称，如果填内容识别不到，下载为未知文件，所以我这里就不填为空
        a.href = URL.createObjectURL(blob)
        a.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }))// 兼容火狐
      } else { // 谷歌兼容下载
        img.src = myCanvas[0].toDataURL('image/jpg')
        // a.href = myCanvas[0].toDataURL('image/png').replace('image/png', 'image/octet-stream')
        a.href = img.src
        // 设置下载文件的名字
        a.download = '下载'
        // 点击
        a.click()
      }
    },
    beforeInit() {
      this.url = 'api/team-list'
      const sort = 'create_date'
      this.params = { page: this.page, size: this.size, sort: sort }
      // 根据用户等级，用户角色查询团队信息
      if (this.user.user_id && this.user.user_id !== null && this.user.user_id !== undefined && this.user.user_id !== '') {
        this.params['user_id'] = this.user.user_id
        this.params['team_id'] = this.user.team_id
        this.params['member_type'] = this.user.member_type
      }
      // 查询条件
      const query = this.query
      const team_name = query.team_name
      const leader_name = query.leader_name
      const phone = query.phone
      const state = query.state
      if (team_name && team_name !== '' && team_name !== null) {
        this.params['team_name'] = team_name
      }
      if (leader_name && leader_name !== '' && leader_name !== null) {
        this.params['leader_name'] = leader_name
      }
      if (phone && phone !== '' && phone !== null) {
        this.params['phone'] = phone
      }
      if (state && state !== '' && state !== null) {
        this.params['state'] = state
      }
      return true
    },
    enterBank(obj) {
      this.$router.push({ path: '/team/teamDetail', query: {
        type: 2, 'team_id': obj.team_id
      }})
    },
    getcode(obj) {
      console.log(obj)
      this.code_show = true
      this.teamcode = obj
      this.teamname = obj.team_name
      this.getQrocde(obj.team_id)
    },
    submit() {
      this.code_show = false
    },
    subDelete(info) {
      // 删除
      this.delLoading = true
      const data = { 'team_id': info.team_id }
      deleteTeam(data).then(() => {
        this.delLoading = false
        this.$refs[info.team_id].doClose()
        this.dleChangePage()
        this.init()
        this.$notify({
          title: '删除成功',
          type: 'success',
          duration: 2500
        })
      }).catch(() => {
        this.delLoading = false
        this.$refs[info.team_id].doClose()
      })
    },
    subRelease(info) {

    },
    add() {
      this.$router.push({ path: '/team/teamDetail', query: {
        type: 1
      }})
    },
    resetQuery() {
      // 重置，重置表单，刷新页面
      this.$refs['query'].resetFields()
      this.query = {
        team_name: '',
        leader_name: '',
        phone: '',
        state: ''
      }
      this.init()
    }
  }
}
</script>

<style scoped>
  .operate-container{
    float: right;
  }
  .btn{
    display: inline-block;
    width: 50px;
    color: #00a0e9;
    cursor: pointer;
  }
  .downcode{
    display: inline-block;
    width: 110px;
    color: #ffffff;
    background-color: #00a0e9;
    border-radius: 5px;
    text-align: center;
    height: 28px;
    line-height: 28px;
    margin-top:8px;
    cursor: pointer;
  }
  .code{
    width: 130px;
    height: 130px;
    margin-bottom: 10px;
  }
  .code_con{
    display: flex;
    align-items: center;
    flex-direction: column;
  }
  .teamname{

  }
</style>
